package com.wjy.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author ybxxszl
 * @date 2019年4月23日
 * @description RestTemplate工具类
 */
@Component
public class RestTemplateUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private JacksonUtil jacksonUtil;

    public <T> T get(String url, Class<T> responseType) throws Exception {
        try {
            T t = restTemplate.getForObject(url, responseType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("RestTemplate请求get异常");
        }
    }

    public <T> T post(String url, Object body, Class<T> responseType) throws Exception {
        try {
            T t = restTemplate.postForObject(url, jacksonUtil.toString(body), responseType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("RestTemplate请求post异常");
        }
    }

    public <T> T getWithHeader(String url, Class<T> responseType) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        try {
            ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, responseType);
            T t = responseEntity.getBody();
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("RestTemplate请求getWithHeader异常");
        }
    }

    public <T> T postWithHeader(String url, Object body, Class<T> responseType) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(jacksonUtil.toString(body), headers);
        try {
            ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, responseType);
            T t = responseEntity.getBody();
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("RestTemplate请求postWithHeader异常");
        }
    }

}
